﻿define([
    'Wjs/Wjs'
],
function () {
    'use strict';

    return Wjs.defineOnce({

        type: 'Loader',

        internal: {

            'abstract': [

                'getData'
            ]
        },

        setScope: function (scope) {

            this.scope = scope;

            return this;
        },

        onData: function (fcn) {

            this.dataHandler = Wjs.chain(this.dataHandler, fcn);

            return this;
        },

        onNoData: function (fcn) {

            this.noDataHandler = Wjs.chain(this.noDataHandler, fcn);

            return this;
        },

        setContentType: function (contentType) {

            this.contentType = contentType;

            return this;
        },

        getContentType: function () {

            return this.contentType;
        },

        handleDataEvents: function (data, callback) {
            var contentType = this.getContentType();

            if (this.isEmptyData(data, contentType) && this.noDataHandler) { // No data was returned

                this.noDataHandler.call(this.scope);
            }
            else if (this.dataHandler) { // Data was returned

                this.dataHandler.call(this.scope, data, contentType);
            }

            if (callback) { // If there is a callback call it on the scope

                callback.call(this.scope, data, contentType);
            }
        },

        isEmptyData: function (data, contentType) {

            if (!Wjs.isDefined(data)) {

                return true;
            }

            switch (contentType) {
                case 'json':
                    {
                        if (Wjs.isEmpty(data) ||
                            (Wjs.isArray(data) && data.length === 0)) {

                            return true;
                        }
                    }
                    break;
                case 'xml':
                    {
                        if (data.childNodes.length === 0) {

                            return true;
                        }
                    }
                    break;
                default:
                    {
                        if (data === '') {

                            return true;
                        }
                    }
                    break;
            }

            return false;
        },

        clone: function () {
            var cloned = Wjs.new(this.type);

            // cloned.scope = this.scope; // The scope is set by Loadable, we don't want to set it to the original one

            cloned.dataHandler = this.dataHandler;

            cloned.noDataHandler = this.noDataHandler;

            cloned.contentType = this.contentType;

            return cloned;
        }

    });
});